package com.wangyadong.hobby.schedule.jobtask.javasync;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/11/159:42
 **/
public final class IntegerAccmulatorExample2 {

    private final int init;

    public IntegerAccmulatorExample2(int init) {
        this.init = init;
    }

    public int getValue() {
        return this.init;
    }

    public IntegerAccmulatorExample2(IntegerAccmulatorExample2 integerAccmulatorExample2, int i) {
        this.init = integerAccmulatorExample2.getValue() + i;
    }

    public IntegerAccmulatorExample2 add(int i) {
        return new IntegerAccmulatorExample2(this, i);
    }


    public static void main(String[] args) {
        IntegerAccmulatorExample2 accmulatorExample2 = new IntegerAccmulatorExample2(0);
        IntStream.range(0, 3).forEach(i -> new Thread(() -> {
            int inc = 0;
            while (true) {
                int oldValue = accmulatorExample2.getValue();
                int result = accmulatorExample2.add(inc).getValue();
                System.out.println("the old value is" + oldValue + " add " + inc + " result is " + result);
                if ((oldValue + inc) != result) {
                    System.out.println("Error" + "the old value is" + oldValue + " add " + inc + " result is " + result);
                }
                inc++;
                slowly();

            }
        }).start());
    }

    private static void slowly() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
